import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { User } from '../schemas/users/user.schema';
import * as bcrypt from 'bcryptjs'; import { JwtService } from '@nestjs/jwt';
import axios from 'axios';
import * as xml2js from 'xml2js';
import e from 'express';

@Injectable()
export class AuthService {
  constructor(
    @InjectModel(User.name) private userModel: Model<User>,
    private jwtService: JwtService
  ) { }

  // 生成6位数字验证码
  private generateCode(): string {
    return Math.floor(100000 + Math.random() * 900000).toString();
  }

  // 发送验证码（模拟实现）
  async sendSMSCode(mobile: string): Promise<void> {
    const code = this.generateCode();
    const expireAt = new Date(Date.now() + 5 * 60 * 1000); // 5分钟有效期

    await this.userModel.updateOne(
      { mobile },
      {
        $set: {
          smsCode: await bcrypt.hash(code, 6), // 低强度哈希存储
          smsCodeExpire: expireAt
        }
      },
      { upsert: true } // 不存在则创建
    );
    // 调用第三方短信服务API
    // const url = 'https://106.ihuyi.com/webservice/sms.php?method=Submit';
    // const data = new URLSearchParams({
    //   account: process.env.SMS_API_ID, // 确保在.env文件中有相应的环境变量
    //   password: process.env.SMS_API_KEY, // 或者动态生成的密码
    //   mobile: mobile,
    //   content: `您的验证码是：${code}。请不要把验证码泄露给其他人。`,
    // });

    // try {
    //   const response = await axios.post(url, data, {
    //     headers: {
    //       'Content-Type': 'application/x-www-form-urlencoded',
    //     },
    //     responseType: 'text', // 设置响应类型为文本，因为我们期望接收XML格式的数据
    //   });

    //   // 解析XML响应
    //   const parser = new xml2js.Parser();
    //   const result = await parser.parseStringPromise(response.data);
      
    //   if (result.SubmitResult.code[0] === '2') { // 检查code字段是否为'2'，表示成功
    //     console.log('短信发送成功:', result.SubmitResult.smsid[0]);
    //   } else {
    //     console.error('短信发送失败:', result.SubmitResult.msg[0]);
    //     throw new Error(`短信发送失败: ${result.SubmitResult.msg[0]}`);
    //   }
    // } catch (error) {
    //   console.error('发送短信时出错:', error.message);
    //   throw new Error('发送短信时遇到问题，请稍后再试');
    // }
    // 实际应调用短信服务商API
    console.log(`【模拟短信】验证码：${code}，5分钟内有效`);
  }

  // 验证码登录/注册
  async loginBySMS(mobile: string, code: string): Promise<any> {
    const user = await this.userModel.findOne({ mobile })
      .select('+smsCode +smsCodeExpire');
    console.log(user,'user')
    if (!user || !user.smsCode || !user.smsCodeExpire) {
      throw new Error('验证码无效');
    }

    // 校验验证码及有效期
    const isCodeValid = await bcrypt.compare(code, user.smsCode);
    const isExpired = user.smsCodeExpire < new Date();
console.log(isCodeValid,isExpired)
    if (!isCodeValid || isExpired) {
      throw new Error('验证码错误或已过期');
    }

    return this.generateToken(user);
  }
  // 密码登录
  async loginByPassword(mobile: string, password: string): Promise<any> {
    const user = await this.userModel.findOne({ mobile })
      .select('+password');

    if (!user || !user.password) {
      throw new Error('用户不存在');
    }

    const isMatch = await bcrypt.compare(password, user.password);
    if (!isMatch) throw new Error('密码错误');

    return this.generateToken(user);
  }

  // 设置密码
  async setPassword(mobile: string, password: string): Promise<void> {
    const hashed = await bcrypt.hash(password, 10);
    await this.userModel.updateOne(
      { mobile },
      { $set: { password: hashed } }
    );
  }

  // 生成JWT
  private generateToken(user: User): { token: string } {
    const payload = { mobile: user.mobile, sub: user._id ,roles:user.roles};
    return { token: this.jwtService.sign(payload) };
  }

  // 设置角色

  async setRolesByMobile(mobile: string, roles: string[]): Promise<void> {
    const user = await this.userModel.findOne({ mobile });
    if (!user) throw new Error('User not found');
    user.roles = roles; // 直接替换角色数组
    await user.save();
  }

  // 验证码注册
  async registerBySMS(
    mobile: string,
    code: string,
    name: string,
    province: string,
    gender?: string,
    school?: string,
    graduationYear?: string,
    password?: string,
  ): Promise<{ token: string }> {
    // 验证用户是否存在且验证码正确
    console.log(mobile,code,name,province,gender,school,graduationYear,'registerBySMS')
    const user = await this.userModel.findOne({ mobile })
      .select('+smsCode +smsCodeExpire');
  
    if (!user || !user.smsCode || !user.smsCodeExpire) {
      throw new Error('验证码无效');
    }
  
    // 校验验证码
    const isCodeValid = await bcrypt.compare(code, user.smsCode);
    const isExpired = user.smsCodeExpire < new Date();
    if (!isCodeValid || isExpired) {
      throw new Error('验证码错误或已过期');
    }
  
    // 补全用户信息
    user.name = name;
    user.province = province;
    user.password = await bcrypt.hash(password, 10);
    if (gender) user.gender = gender;
    if (school) user.school = school;
    if (graduationYear) user.graduationYear = graduationYear;
  
    // 清除验证码
    user.smsCode = undefined;
    user.smsCodeExpire = undefined;
  
    await user.save();
  
    // 生成 Token
    return this.generateToken(user);
  }
}